import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Spin, message } from 'antd';
import { 
  CalendarOutlined, 
  DollarOutlined, 
  TeamOutlined, 
  ReadOutlined,
  StarOutlined,
  CommentOutlined
} from '@ant-design/icons';
import ReactEcharts from 'echarts-for-react';
import request from '../../utils/request';
import './index.less';
import useAuthStore from '../../stores/authStore';

const Analytics = () => {
  const [loading, setLoading] = useState(true);
  const [statistics, setStatistics] = useState({
    totalBookings: 0,
    totalRevenue: 0,
    totalStudents: 0,
    totalCourses: 0,
    avgRating: 0,
    totalComments: 0
  });
  const [bookingTrend, setBookingTrend] = useState([]);
  const [categoryData, setCategoryData] = useState([]);
  const [courseEnrollments, setCourseEnrollments] = useState([]);
  const [ratingDistribution, setRatingDistribution] = useState([]);
  const [activityHeatmap, setActivityHeatmap] = useState([]);
  const { user } = useAuthStore();

  // 获取统计数据
  const fetchStatistics = async () => {
    try {
      if (!user?.id) {
        message.error('未获取到教师信息');
        return;
      }
      const res = await request.get('/api/admin/statistics', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setStatistics(res.data);
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  // 获取预约趋势数据
  const fetchBookingTrend = async () => {
    try {
      const res = await request.get('/api/admin/booking-trend', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setBookingTrend(res.data);
      }
    } catch (error) {
      console.error('获取预约趋势失败:', error);
    }
  };

  // 获取课程分类数据
  const fetchCategoryData = async () => {
    try {
      const res = await request.get('/api/admin/category-statistics', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setCategoryData(res.data);
      }
    } catch (error) {
      console.error('获取分类统计失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取课程报名人数数据
  const fetchCourseEnrollments = async () => {
    try {
      const res = await request.get('/api/admin/course-enrollments', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setCourseEnrollments(res.data);
      }
    } catch (error) {
      console.error('获取课程报名数据失败:', error);
    }
  };

  // 获取评分分布数据
  const fetchRatingDistribution = async () => {
    try {
      const res = await request.get('/api/admin/rating-distribution', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setRatingDistribution(res.data);
      }
    } catch (error) {
      console.error('获取评分分布失败:', error);
    }
  };

  // 获取活跃度热力图数据
  const fetchActivityHeatmap = async () => {
    try {
      const res = await request.get('/api/admin/activity-heatmap', {
        params: { teacherId: user.id }
      });
      if (res.code === 0) {
        setActivityHeatmap(res.data);
      }
    } catch (error) {
      console.error('获取活跃度数据失败:', error);
    }
  };

  useEffect(() => {
    if (user?.id) {
      Promise.all([
        fetchStatistics(),
        fetchBookingTrend(),
        fetchCategoryData(),
        fetchCourseEnrollments(),
        fetchRatingDistribution(),
        fetchActivityHeatmap()
      ]);
    }
  }, [user]);

  // 预约趋势图配置
  const getTrendOption = () => ({
    title: {
      text: '预约趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: bookingTrend.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: bookingTrend.map(item => item.count),
      type: 'line',
      smooth: true
    }]
  });

  // 课程分类饼图配置
  const getCategoryOption = () => ({
    title: {
      text: '课程分类分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [{
      type: 'pie',
      radius: '65%',
      data: categoryData.map(item => ({
        name: item.name,
        value: item.count
      })),
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  // 课程报名柱状图配置
  const getCourseEnrollmentOption = () => ({
    title: {
      text: '课程报名人数'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: courseEnrollments.map(item => item.title),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: courseEnrollments.map(item => item.count),
      type: 'bar'
    }]
  });

  // 评分分布图配置
  const getRatingDistributionOption = () => ({
    title: {
      text: '课程评分分布'
    },
    tooltip: {
      trigger: 'item'
    },
    radar: {
      indicator: [
        { name: '1分', max: Math.max(...ratingDistribution) },
        { name: '2分', max: Math.max(...ratingDistribution) },
        { name: '3分', max: Math.max(...ratingDistribution) },
        { name: '4分', max: Math.max(...ratingDistribution) },
        { name: '5分', max: Math.max(...ratingDistribution) }
      ],
      radius: '65%',
      center: ['50%', '50%']
    },
    series: [{
      type: 'radar',
      data: [{
        value: ratingDistribution,
        name: '评分数量',
        areaStyle: {
          color: 'rgba(64,158,255,0.3)'
        },
        lineStyle: {
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      }]
    }]
  });

  // 活跃度热力图配置
  const getActivityHeatmapOption = () => ({
    title: {
      text: '学生活跃度分布'
    },
    tooltip: {
      position: 'top'
    },
    grid: {
      height: '50%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: ['早上', '下午', '晚上'],
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%'
    },
    series: [{
      name: '活跃度',
      type: 'heatmap',
      data: activityHeatmap,
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  });

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className="analytics-page">
      <Row gutter={[16, 16]}>
        <Col span={6}>
          <Card>
            <Statistic
              title="平均评分"
              value={Number(statistics.avgRating).toFixed(1)}
              prefix={<StarOutlined />}
              suffix={
                <div style={{ marginLeft: '8px' }}>
                  {[1, 2, 3, 4, 5].map(star => (
                    <StarOutlined 
                      key={star}
                      style={{ 
                        color: star <= Math.round(statistics.avgRating) ? '#1890ff' : '#d9d9d9',
                        marginLeft: '2px' 
                      }} 
                    />
                  ))}
                </div>
              }
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="评价总数"
              value={statistics.totalComments}
              prefix={<CommentOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="学员数量"
              value={statistics.totalStudents}
              prefix={<TeamOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="课程数量"
              value={statistics.totalCourses}
              prefix={<ReadOutlined style={{ color: '#1890ff' }} />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="chart-row">
        <Col span={16}>
          <Card>
            <ReactEcharts option={getTrendOption()} style={{ height: '400px' }} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <ReactEcharts option={getCategoryOption()} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="chart-row">
        <Col span={12}>
          <Card>
            <ReactEcharts option={getCourseEnrollmentOption()} style={{ height: '400px' }} />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <ReactEcharts option={getRatingDistributionOption()} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="chart-row">
        <Col span={24}>
          <Card>
            <ReactEcharts option={getActivityHeatmapOption()} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Analytics; 